from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from app01.templates.chat import SparkApi

from rest_framework.views import APIView # 搭建&连接服务器
from rest_framework.response import Response
from rest_framework import status

from .models import User
from .models import Question, Answer, Tag, Comment, Like, User, ChatHistory, UserAuthentication
from .models import AEDEquipment, Knowledge, EquipmentKnowledge

from django.contrib.contenttypes.models import ContentType

import json
import requests
import uuid
from datetime import datetime, timedelta # 处理用户登录验证
#获取csrftoken
from django.http import JsonResponse
from django.middleware.csrf import get_token
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt # 免去scrftoken校验
from django.conf import settings
# AED地图部分
@csrf_exempt
def get_aed_list(request):
    # 从数据库中获取 AED 设备数据
    aed_devices = AEDEquipment.objects.all().values(
        'id', 'name', 'longitude', 'latitude', 'status', 'usage_guide', 'image'
    )
    # 将数据转换为列表
    aed_data = list(aed_devices)

    # 处理 related_knowledge 字段
    for device in aed_data:
        # 获取关联的科普知识
        related_knowledge = Knowledge.objects.filter(
            equipmentknowledge__equipment_id=device['id']
        ).values_list('title', flat=True)
        device['related_knowledge'] = list(related_knowledge)
        # 将相对路径转换为完整 URL
        device['image'] = f'{settings.BASE_URL}/media/{device["image"]}'

    # 返回 JSON 响应
    return JsonResponse({'success': True, 'data': aed_data})

from django.db.models import Q
# 搜索aed设备
@csrf_exempt
def search_aed(request):
    if request.method == 'GET':
        # 获取查询参数
        keyword = request.GET.get('keyword', '').strip()
        latitude = request.GET.get('latitude', None)
        longitude = request.GET.get('longitude', None)

        # 构建查询条件
        query = Q()
        if keyword:
            query &= Q(name__icontains=keyword) | Q(usage_guide__icontains=keyword)
        if latitude and longitude:
            # 这里可以根据经纬度进行范围查询（如果需要）
            pass

        # 从数据库中获取符合条件的 AED 设备数据
        aed_devices = AEDEquipment.objects.filter(query).values(
            'id', 'name', 'longitude', 'latitude', 'status', 'usage_guide', 'image'
        )
        # 将数据转换为列表
        aed_data = list(aed_devices)

        # 处理 related_knowledge 字段
        for device in aed_data:
            # 获取关联的科普知识
            related_knowledge = Knowledge.objects.filter(
                equipmentknowledge__equipment_id=device['id']
            ).values_list('title', flat=True)
            device['related_knowledge'] = list(related_knowledge)
            # 将相对路径转换为完整 URL
            if device['image']:
                device['image'] = f'{settings.BASE_URL}/media/{device["image"]}'
            else:
                device['image'] = None

        # 返回 JSON 响应
        return JsonResponse({'success': True, 'data': aed_data})
    else:
        return JsonResponse({'success': False, 'message': 'Invalid request method'}, status=400)



@csrf_exempt
def getToken(request):
    print(request.method)
    token = get_token(request)
    return JsonResponse({'token': token})

def user_list(request):
    users = User.objects.all()
    return render(request, 'test.html', {'users': users})


class TagList(View):
    def get(self, request):
        tags = Tag.objects.all()
        data = [{'id': tag.id, 'name': tag.name} for tag in tags]
        return JsonResponse(data, safe=False)


def gotoTest(request):
    courses_data = [
        {'id': '22130130', 'name': '沈博'},
        {'id': '22130131', 'name': '张博'},
        {'id': '22130132', 'name': '李博'},
        {'id': '22130133', 'name': '赵博'},
        {'id': '22130134', 'name': '吴博'},
        {'id': '22130135', 'name': '钱博'},
        {'id': '22130136', 'name': '孙博'},
    ]
    if request.method == 'GET':
        course_id = '22130130'
        course_name = '沈博'
        course_data = {'id': course_id, 'name': course_name}
        return JsonResponse(courses_data, safe=False)

class MyAPI(APIView):
    def get(self, request):
        # 返回一个简单的响应
        data = {"message": "Hello from Django (GET),欢迎访问AED急救小程序"}
        return Response(data, status=status.HTTP_200_OK)

    def post(self, request):
        # 获取POST请求的数据并返回
        data = request.data
        response_data = {"received_data": data}
        return Response(response_data, status=status.HTTP_201_CREATED)

"""" 用户问答模块 """
class QuestionList(View):
    def get(self, request):
        questions = Question.objects.all()
        data = []
        for q in questions:
            data.append({
                'id': q.id,
                'title': q.title,
                'content': q.content,
                'user': {'id': q.user.id, 'nickname': q.user.nickname},
                'tags': [{'id': t.id, 'name': t.name} for t in q.tags.all()],
                'created_at': q.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': q.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
                'answers': [{
                    'id': a.id,
                    'content': a.content,
                    'user': {'id': a.user.id, 'nickname': a.user.nickname},
                    'is_accepted': a.is_accepted,
                    'created_at': a.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'updated_at': a.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                } for a in q.answers.all()]
            })
        return JsonResponse(data, safe=False)

class QuestionCreate(View):
    def post(self, request):
        data = json.loads(request.body)
        user = User.objects.get(id=data['user'])
        question = Question.objects.create(
            title=data['title'],
            content=data['content'],
            user=user
        )
        for tag_id in data['tags']:
            tag = Tag.objects.get(id=tag_id)
            question.tags.add(tag)
        return JsonResponse({'id': question.id}, status=201)

class AnswerList(View):
    def get(self, request):
        answers = Answer.objects.all()
        data = []
        for a in answers:
            data.append({
                'id': a.id,
                'content': a.content,
                'user': {'id': a.user.id, 'nickname': a.user.nickname},
                'is_accepted': a.is_accepted,
                'created_at': a.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': a.updated_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        return JsonResponse(data, safe=False)

class AnswerCreate(View):
    def post(self, request):
        data = json.loads(request.body)
        user = User.objects.get(id=data['user'])
        question = Question.objects.get(id=data['question'])
        answer = Answer.objects.create(
            content=data['content'],
            user=user,
            question=question
        )
        return JsonResponse({'id': answer.id}, status=201)

@method_decorator(csrf_exempt, name='dispatch')
class LikeAnswer(View):
    def post(self, request, answer_id):
        try:
            data = json.loads(request.body)
            user_id = data.get('user')  # 获取用户 ID
            user = User.objects.get(id=user_id)  # 获取用户对象
            answer = Answer.objects.get(id=answer_id)  # 获取回答对象

            # 获取 ContentType 对象
            content_type = ContentType.objects.get_for_model(Answer)

            # 检查是否已经点赞
            like, created = Like.objects.get_or_create(
                user=user,
                content_type=content_type,
                object_id=answer.id
            )

            if created:
                return JsonResponse({'message': '点赞成功'}, status=201)
            else:
                return JsonResponse({'message': '已经点赞过'}, status=200)
        except User.DoesNotExist:
            return JsonResponse({'error': '用户不存在'}, status=404)
        except Answer.DoesNotExist:
            return JsonResponse({'error': '回答不存在'}, status=404)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)


# 讯飞星火api调试
@csrf_exempt
def ask_question(request):
    if request.method == 'POST':
        # 解析小程序传入的 JSON 数据
        data = json.loads(request.body)
        question = data.get('question')
        user_id = data.get('user_id')  # 获取用户 ID
        session_id = data.get('session_id')  # 获取会话 ID

        # 获取历史对话记录
        history = ChatHistory.objects.filter(user_id=user_id, session_id=session_id).order_by('created_at')
        messages = [{"role": "user", "content": question}]  # 当前问题

        # 将历史对话记录添加到 messages 中
        for record in history:
            messages.insert(0, {"role": "user", "content": record.message})
            messages.insert(1, {"role": "assistant", "content": record.response})

        # 调用讯飞星火大模型 API
        url = "https://spark-api-open.xf-yun.com/v1/chat/completions"
        headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer BJIuXaKlgarRTwCExoiE:sypbtiLkmRlfHGYadsxs"  # 替换为实际的 API Key
        }
        payload = {
            "model": "lite",  # 根据需要选择模型版本
            "messages": messages,  # 包含历史对话的上下文
            "max_tokens": 4096,
            "temperature": 0.5,
            "stream": False  # 非流式响应
        }

        # 发送请求
        response = requests.post(url, headers=headers, json=payload)
        result = response.json()

        # 提取 AI 的回复
        if response.status_code == 200:
            ai_response = result['choices'][0]['message']['content']

            # 将问题和答案保存到数据库
            try:
                user = User.objects.get(id=user_id)  # 获取用户对象
                ChatHistory.objects.create(
                    user=user,
                    message=question,
                    response=ai_response,
                    session_id=session_id  # 保存会话 ID
                )
                return JsonResponse({'status': 'success', 'response': ai_response})
            except User.DoesNotExist:
                return JsonResponse({'status': 'error', 'message': '用户不存在'}, status=404)
        else:
            return JsonResponse({'status': 'error', 'message': 'AI 服务调用失败'}, status=500)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=400)


@csrf_exempt
def login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        avatarUrl = data.get('avatarUrl')
        nickName = data.get('nickName')

        # 生成唯一的用户 ID 和认证令牌
        userId = str(uuid.uuid4())
        authToken = str(uuid.uuid4())

        # 保存用户信息到 User 表
        user = User.objects.create(
            openid=userId,  # 使用 userId 作为 openid
            nickname=nickName,
            avatar_url=avatarUrl
        )

        # 保存认证令牌到 UserAuthentication 表
        UserAuthentication.objects.create(
            user=user,
            auth_token=authToken
        )

        return JsonResponse({'status': 'success', 'userId': userId, 'authToken': authToken})
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'})

# 检查用户登录状态
def checkLoginStatus(request):
    authToken = request.GET.get('authToken')
    try:
        authInfo = UserAuthentication.objects.get(auth_token=authToken)
        return JsonResponse({'status': 'success'})
    except UserAuthentication.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '登录状态已失效'})

# 修改用户信息
@csrf_exempt
def updateProfile(request):
    if request.method == 'POST':
        # 初始化 avatar 变量
        avatar = None

        # 解析 JSON 数据
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            userId = data.get('userId')
            nickName = data.get('nickName')
        # 解析表单数据
        else:
            userId = request.POST.get('userId')
            nickName = request.POST.get('nickName')
            avatar = request.FILES.get('avatar')

        print(f"Received userId: {userId}")  # 打印传入的 userId
        try:
            user = User.objects.get(openid=userId)
            if nickName:
                user.nickname = nickName
            if avatar:
                user.avatar_url = avatar.url
            user.save()
            return JsonResponse({'status': 'success'})
        except User.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': '用户不存在'})
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'})




#### 普通管理员部分
def aed_list_view(request):
    return render(request, 'map/aed_list.html')

def admin_aed_list(request):
   return render(request, 'map/admin_aed_list.html')

"""
实现ChatGPT
appid = "XXXXXXXX"
api_secret = "XXXXXXXXXXXXXXXXXXXXXXXX"
api_key = "XXXXXXXXXXXXXXXXXXXXXXXX"

domain = "generalv3.5"
Spark_url = "wss://spark-api.xf-yun.com/v3.5/chat"

class ChatView(View):
    def post(self, request):
        user_input = request.POST.get("input", "")
        if not user_input:
            return JsonResponse({"error": "No input provided"}, status=400)

        # 获取当前会话中的文本上下文
        text = request.session.get('text', [])
        question = checklen(getText(text, "user", user_input))

        SparkApi.answer = ""

        try:
            SparkApi.main(appid, api_key, api_secret, Spark_url, domain, question)
            response = getText(text, "assistant", SparkApi.answer)
            request.session['text'] = text  # 更新会话中的文本
            return JsonResponse({"answer": SparkApi.answer})
        except Exception as e:
            return JsonResponse({"error": str(e)}, status=500)

def getText(text, role, content):
    jsoncon = {"role": role, "content": content}
    text.append(jsoncon)
    return text

def getlength(text):
    return sum(len(content["content"]) for content in text)

def checklen(text):
    while getlength(text) > 8000:
        text.pop(0)  # 删除最旧的消息
    return text

def index(request):
    return render(request, 'index.html')  # 确保 'index.html' 在你的模板目录下
"""